<template>
  <div class="user-blacklist">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户黑名单管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleAdd">添加黑名单</el-button>
            <el-button type="success" @click="handleBatchRemove"
              >批量移除</el-button
            >
            <el-button type="info" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="限制类型">
          <el-select v-model="searchForm.type" placeholder="请选择限制类型">
            <el-option label="永久封禁" value="permanent" />
            <el-option label="临时封禁" value="temporary" />
            <el-option label="功能限制" value="restricted" />
          </el-select>
        </el-form-item>
        <el-form-item label="添加时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="blacklist"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无黑名单数据" 
              :image-size="200"
            >
              <div class="empty-text">没有添加任何用户到黑名单</div>
              <div class="empty-subtext">您可以将违规用户添加到黑名单进行管理</div>
              <el-button type="primary" @click="handleAdd" class="mt-4">添加黑名单</el-button>
            </el-empty>
          </div>
        </template>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column
          prop="username"
          label="用户名"
          width="120"
          sortable="custom"
        />
        <el-table-column
          prop="type"
          label="限制类型"
          width="100"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reason"
          label="限制原因"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="startTime"
          label="开始时间"
          width="160"
          sortable="custom"
        />
        <el-table-column
          prop="endTime"
          label="结束时间"
          width="160"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ row.type === "permanent" ? "永久" : row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleRemove(row)">
                移除
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑黑名单' : '添加黑名单'"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户" prop="userId" v-if="!isEdit">
          <el-select
            v-model="form.userId"
            filterable
            remote
            :remote-method="searchUsers"
            placeholder="请输入用户名搜索"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
              <span>{{ item.username }}</span>
              <span class="user-info">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="限制类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择限制类型">
            <el-option label="永久封禁" value="permanent" />
            <el-option label="临时封禁" value="temporary" />
            <el-option label="功能限制" value="restricted" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="限制时间"
          prop="timeRange"
          v-if="form.type !== 'permanent'"
        >
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="限制原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入限制原因"
          />
        </el-form-item>
        <el-form-item label="限制说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入限制说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="黑名单详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{
          currentDetail.userId
        }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{
          currentDetail.username
        }}</el-descriptions-item>
        <el-descriptions-item label="限制类型">
          <el-tag :type="getTypeTag(currentDetail.type)">
            {{ getTypeLabel(currentDetail.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{
          currentDetail.startTime
        }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">
          {{
            currentDetail.type === "permanent" ? "永久" : currentDetail.endTime
          }}
        </el-descriptions-item>
        <el-descriptions-item label="操作人">{{
          currentDetail.operator
        }}</el-descriptions-item>
        <el-descriptions-item label="限制原因" :span="2">{{
          currentDetail.reason
        }}</el-descriptions-item>
        <el-descriptions-item label="限制说明" :span="2">{{
          currentDetail.description
        }}</el-descriptions-item>
        <el-descriptions-item label="操作记录" :span="2">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in currentDetail.activities"
              :key="index"
              :timestamp="activity.time"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/user";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

// API接口
const API = {
  getBlacklist: (params) => service.get('/admin/blacklist', { params }),
  getBlacklistDetail: (id) => service.get(`/admin/blacklist/${id}`),
  addToBlacklist: (data) => service.post('/admin/blacklist', data),
  updateBlacklistItem: (id, data) => service.put(`/admin/blacklist/${id}`, data),
  removeFromBlacklist: (id) => service.delete(`/admin/blacklist/${id}`),
  batchRemoveFromBlacklist: (ids) => service.post('/admin/blacklist/batch-remove', { ids }),
  searchUsers: (params) => service.get('/admin/users/search', { params })
};

// 用户存储
const userStore = useUserStore();

// 搜索表单
const searchForm = reactive({
  username: "",
  type: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const blacklist = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedItems = ref([]);

// 添加/编辑对话框
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const form = reactive({
  userId: "",
  type: "",
  timeRange: [],
  reason: "",
  description: "",
});

// 用户选项
const userOptions = ref([]);

// 表单验证规则
const rules = {
  userId: [{ required: true, message: "请选择用户", trigger: "change" }],
  type: [{ required: true, message: "请选择限制类型", trigger: "change" }],
  timeRange: [
    {
      required: true,
      message: "请选择限制时间",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (form.type === "permanent") {
          callback();
        } else if (!value || value.length !== 2) {
          callback(new Error("请选择限制时间"));
        } else {
          callback();
        }
      },
    },
  ],
  reason: [{ required: true, message: "请输入限制原因", trigger: "blur" }],
};

// 详情对话框
const detailDialogVisible = ref(false);
const currentDetail = ref({});

// 获取限制类型标签
const getTypeLabel = (type) => {
  const types = {
    permanent: "永久封禁",
    temporary: "临时封禁",
    restricted: "功能限制",
  };
  return types[type] || type;
};

// 获取限制类型标签样式
const getTypeTag = (type) => {
  const types = {
    permanent: "danger",
    temporary: "warning",
    restricted: "info",
  };
  return types[type] || "";
};

// 搜索用户
const searchUsers = async (query) => {
  if (query) {
    try {
      const res = await API.searchUsers({ keyword: query });
      userOptions.value = (res.data || []).map((user) => ({
        id: user.id,
        username: user.username,
        phone: user.phone,
      }));
    } catch (error) {
      console.error("搜索用户失败：", error);
      ElMessage.error("搜索用户失败");
      userOptions.value = [];
    }
  } else {
    userOptions.value = [];
  }
};

// 搜索黑名单
const handleSearch = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.username,
      type: searchForm.type,
      startTime: searchForm.dateRange?.[0],
      endTime: searchForm.dateRange?.[1],
      sortBy: sortConfig.value.prop,
      sortOrder: sortConfig.value.order,
    };

    try {
      const res = await API.getBlacklist(params);
      blacklist.value = res.list || [];
      total.value = res.total || 0;
    } catch (error) {
      console.error("API请求失败，使用测试数据", error);
      // 测试数据
      const mockData = {
        list: [
          {
            id: 1,
            username: "张三",
            type: "permanent",
            reason: "多次违规发布不当内容",
            startTime: "2024-03-15 10:00:00",
            endTime: null,
            operator: "管理员A",
            description: "用户多次发布违规内容,经警告无效",
            activities: [
              { time: "2024-03-15 10:00:00", content: "添加到黑名单" },
              { time: "2024-03-14 15:30:00", content: "第三次警告" },
            ],
          },
          {
            id: 2,
            username: "李四",
            type: "temporary",
            reason: "恶意攻击其他用户",
            startTime: "2024-03-14 14:20:00",
            endTime: "2024-04-14 14:20:00",
            operator: "管理员B",
            description: "用户在评论区恶意攻击其他用户",
            activities: [
              { time: "2024-03-14 14:20:00", content: "添加到黑名单" },
            ],
          },
          {
            id: 3,
            username: "王五",
            type: "restricted",
            reason: "发布垃圾广告",
            startTime: "2024-03-13 09:15:00",
            endTime: "2024-03-20 09:15:00",
            operator: "管理员A",
            description: "用户频繁发布广告信息",
            activities: [
              { time: "2024-03-13 09:15:00", content: "添加到黑名单" },
            ],
          },
          {
            id: 4,
            username: "赵六",
            type: "permanent",
            reason: "账号被盗风险",
            startTime: "2024-03-12 16:40:00",
            endTime: null,
            operator: "管理员C",
            description: "账号存在安全风险,暂时封禁",
            activities: [
              { time: "2024-03-12 16:40:00", content: "添加到黑名单" },
            ],
          },
          {
            id: 5,
            username: "钱七",
            type: "temporary",
            reason: "违规商业推广",
            startTime: "2024-03-11 11:30:00",
            endTime: "2024-03-25 11:30:00",
            operator: "管理员B",
            description: "未经许可进行商业推广",
            activities: [
              { time: "2024-03-11 11:30:00", content: "添加到黑名单" },
            ],
          },
        ],
        total: 5,
      };
      blacklist.value = mockData.list;
      total.value = mockData.total;
    }
  } catch (error) {
    console.error("获取黑名单列表失败：", error);
    ElMessage.error("获取黑名单列表失败");
  } finally {
    loading.value = false;
  }
};

// 排序配置
const sortConfig = ref({
  prop: "",
  order: "",
});

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.value = { prop, order };
  handleSearch();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  searchForm.dateRange = [];
  handleSearch();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedItems.value = val;
};

// 添加黑名单
const handleAdd = () => {
  isEdit.value = false;
  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  form.timeRange = [];
  dialogVisible.value = true;
};

// 编辑黑名单
const handleEdit = async (row) => {
  isEdit.value = true;
  
  try {
    // 尝试获取完整的黑名单记录详情
    const detail = await API.getBlacklistDetail(row.id);
    Object.assign(form, detail);
  } catch (error) {
    console.error("获取黑名单详情失败，使用表格中的数据", error);
    Object.assign(form, row);
  }
  
  if (form.type !== "permanent" && form.startTime && form.endTime) {
    form.timeRange = [form.startTime, form.endTime];
  } else {
    form.timeRange = [];
  }
  
  dialogVisible.value = true;
};

// 移除黑名单
const handleRemove = async (row) => {
  try {
    await ElMessageBox.confirm("确认将该用户从黑名单中移除吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    try {
      await API.removeFromBlacklist(row.id);
      ElMessage.success("移除成功");
      handleSearch();
    } catch (error) {
      console.error("移除黑名单失败", error);
      ElMessage.error("移除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("操作取消：", error);
    }
  }
};

// 批量移除
const handleBatchRemove = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning("请选择要移除的记录");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确认将选中的 ${selectedItems.value.length} 个用户从黑名单中移除吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    try {
      const ids = selectedItems.value.map((item) => item.id);
      await API.batchRemoveFromBlacklist(ids);
      ElMessage.success("批量移除成功");
      handleSearch();
    } catch (error) {
      console.error("批量移除失败", error);
      ElMessage.error("批量移除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("操作取消：", error);
    }
  }
};

// 导出数据
const exportData = async () => {
  try {
    // 准备导出数据
    const exportItems = blacklist.value.map(item => ({
      'ID': item.id,
      '用户名': item.username,
      '限制类型': getTypeLabel(item.type),
      '限制原因': item.reason,
      '开始时间': item.startTime,
      '结束时间': item.type === 'permanent' ? '永久' : item.endTime,
      '操作人': item.operator,
      '说明': item.description
    }));

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 将数据转换为工作表
    const ws = XLSX.utils.json_to_sheet(exportItems);
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '用户黑名单');
    // 生成Excel文件并下载
    XLSX.writeFile(wb, `用户黑名单_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败：", error);
    ElMessage.error("导出失败");
  }
};

// 查看详情
const viewDetail = async (row) => {
  try {
    const detail = await API.getBlacklistDetail(row.id);
    currentDetail.value = detail;
  } catch (error) {
    console.error("获取黑名单详情失败，使用表格中的数据", error);
    currentDetail.value = row;
  }
  
  detailDialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          ...form,
          startTime: form.timeRange?.[0],
          endTime: form.timeRange?.[1],
        };

        if (isEdit.value) {
          await API.updateBlacklistItem(data.id, data);
          ElMessage.success("更新成功");
        } else {
          await API.addToBlacklist(data);
          ElMessage.success("添加成功");
        }

        dialogVisible.value = false;
        handleSearch();
      } catch (error) {
        console.error("保存失败：", error);
        ElMessage.error("保存失败");
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 页面加载时获取数据
onMounted(() => {
  handleSearch();
});
</script>

<style scoped>
.user-blacklist {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-info {
  margin-left: 10px;
  color: #909399;
  font-size: 13px;
}

:deep(.el-timeline-item__content) {
  color: #606266;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.empty-text {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.empty-subtext {
  margin-bottom: 20px;
  font-size: 14px;
  color: #909399;
}

.mt-4 {
  margin-top: 16px;
}
</style>
